package com.hwl.server.config.rabbitmq;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hwl.server.entity.MailLog;
import com.hwl.server.service.MailLogService;
import com.hwl.server.utils.MailConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class RabbitMQConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Resource
    private CachingConnectionFactory cachingConnectionFactory;
    @Resource
    private MailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 消息确认回调，确认消息是否到broker
             * data 消息唯一标识
             * ack  确认结果
             * cause  失败原因
             */
            @Override
            public void confirm(CorrelationData data, boolean ack, String cause) {
                String msgId = data.getId();
                if (ack) {
                    LOGGER.info("{}======>消息发送成功", msgId);
                    mailLogService.update(new UpdateWrapper<MailLog>()
                            .set("status", MailConstants.SUCCESS)
                            .eq("msgId", msgId));
                } else {
                    LOGGER.error("{}======>消息发送失败", msgId);
                }
            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            /**
             * 消息失败回调
             * returnedMessage各属性：
             * message  消息主题
             * replyCode  响应码
             * replyText  响应描述
             * exchange  交换机
             * routingKey  路由键
             */
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                LOGGER.error("{}======>消息发送到queue时失败", returnedMessage.getMessage().getBody());
            }
        });
        return rabbitTemplate;
    }

    //队列
    @Bean
    public Queue queue() {
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    //交换机
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    //队列和交换机绑定关系
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }
}

